package com.heima.comment.service.impl;

import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentLike;
import com.heima.comment.service.CommentHotService;
import com.heima.comment.service.CommentService;
import com.heima.comment.vos.ApCommentVo;
import com.heima.feigns.user.UserFeign;
import com.heima.model.comment.dtos.CommentDto;
import com.heima.model.comment.dtos.CommentLikeDto;
import com.heima.model.comment.dtos.CommentSaveDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
public class CommentServiceImpl implements CommentService {


    @Autowired
    UserFeign userFeign;

    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 根据文章id查询评论列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findByArticleId(CommentDto dto) {
        //1 参数检查
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Integer size = dto.getSize();
        if ( size == null || size <= 0) {
            dto.setSize(10);
        }
        dto.setSize(Math.min(dto.getSize(), 50));

        List<ApComment> commentList = null;


        // 判断是否是首页  热点评论
        if (dto.getIndex().intValue() == 1) {

            //查询所有的热点评论
            commentList = mongoTemplate.find(
                    Query.query(Criteria
                            .where("entryId").is(dto.getArticleId())
                            .and("type").is(0)
                            .and("flag").is(1))
                            .with(Sort.by(Sort.Order.desc("likes"))),
                    ApComment.class);
            int hotSize = commentList.size();

            //查询普通评论
            List<ApComment>  apComments = mongoTemplate.find(
                    Query.query(Criteria
                            .where("entryId").is(dto.getArticleId())
                            .and("type").is(0)
                            .and("flag").is(0)
                            .and("createdTime").lt(dto.getMinDate()))
                            .limit(dto.getSize() - hotSize)
                            .with(Sort.by(Sort.Order.desc("createdTime"))),
                    ApComment.class);

            //合并评论列表
            commentList.addAll(apComments);

        } else {

            //2 查询评论列表
            commentList = mongoTemplate.find(
                    Query.query(Criteria
                            .where("entryId").is(dto.getArticleId())
                            .and("type").is(0)
                            .and("flag").is(0)
                            .and("createdTime").lt(dto.getMinDate()))
                            .limit(dto.getSize())
                            .with(Sort.by(Sort.Order.desc("createdTime"))),
                    ApComment.class);
        }





        //3 获取当前用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.okResult(commentList);
        }

        //远程调用查询用户信息未登录 直接返回评论列表
        ApUser apUser = userFeign.findUserById(user.getId());
        if (apUser == null) {
            return ResponseResult.okResult(commentList);
        }

        //3.1 登录  回显当前用户是否对评论点赞
        // 获取所有的评论id
        List<String> idList = commentList.stream().map(x -> x.getId()).collect(Collectors.toList());

        // 到评论点赞列表中查询
       List<ApCommentLike> commentLikes = mongoTemplate.find(
                    Query.query(Criteria
                            .where("authorId").is(apUser.getId())
                            .and("commentId").in(idList)
                            .and("operation").is(0)
                    ),
                    ApCommentLike.class);

       // 保存用户回显点赞数据集合
        List<ApCommentVo> apCommentVos = new ArrayList<>();

        if(commentList!=null && commentList.size()>0 && commentLikes!=null
                && commentLikes.size()>0){

            commentList.forEach(comment -> {

                ApCommentVo apCommentVo = new ApCommentVo();
                BeanUtils.copyProperties(comment, apCommentVo);

                // 处理回显问题
                commentLikes.forEach(commentLike -> {
                    // 当前用户对这条评论点赞
                    if (comment.getId().equals(commentLike.getCommentId())) {
                        apCommentVo.setOperation((short) 0);
                    }
                });

                // ******
                apCommentVos.add(apCommentVo);
            });


            return ResponseResult.okResult(apCommentVos);
        }

        //4 返回结果
        return ResponseResult.okResult(commentList);
    }

    @Autowired
    CommentHotService commentHotService;

    /**
     * 点赞某一条评论
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentLikeDto dto) {
        //1 参数校验
        if (dto == null || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2 获取登录用户
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3 查询当前评论是否存在
        ApComment comment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (comment == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "暂无评论");
        }

        //4 查询评论的点赞是否已存在
        ApCommentLike commentLike = mongoTemplate.findOne(
                Query.query(Criteria.where("authorId").is(user.getId())
                        .and("commentId").is(dto.getCommentId())),
                ApCommentLike.class);
        if (commentLike != null && dto.getOperation().intValue() == 0
                && commentLike.getOperation().intValue() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "无需重复点赞");
        }

        //5 点赞
        if (dto.getOperation().intValue() == 0) {
            // 保存点赞数据
            if (commentLike == null) {
                commentLike = new ApCommentLike();
                commentLike.setAuthorId(user.getId());
                commentLike.setCommentId(comment.getId());
            }
            commentLike.setOperation(dto.getOperation());
            mongoTemplate.save(commentLike);  // 保存  修改

            // 保存点赞数值+1  TODO bug 分布式锁  redison / zk 实现分布式锁
            comment.setLikes(comment.getLikes() + 1);
            mongoTemplate.save(comment);  //更新点赞数


            // 计算热点评论  异步调用  点赞数值大于5
            if (comment.getLikes() >= 5 && comment.getFlag().shortValue() == 0) {
                // 异步计算热点评论  多线程异步计算
                commentHotService.hotCommentExecutor(comment.getEntryId(), comment );
            }


        } else {   //6 取消点赞
            commentLike.setOperation((short) 1);
            mongoTemplate.save(commentLike);


            //点赞数值-1
            comment.setLikes(  (comment.getLikes() - 1) < 0 ? 0: comment.getLikes() - 1   );
            mongoTemplate.save(comment);  //更新点赞数
        }


        //7 返回结果
        Map<String, Integer> resultMap = new HashMap<>();
        resultMap.put("likes", comment.getLikes());

        return ResponseResult.okResult(resultMap);
    }

    /**
     * 保存评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        //1 参数校验
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 文本长度限制
        String content = dto.getContent();
        if (StringUtils.isBlank(content) || content.length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"评论内容过长或不存在");
        }
        //  todo 内容安全监测

        //2 获取登录用户
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3 远程调用查询用户信息
        ApUser apUser = userFeign.findUserById(user.getId());
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "非法用户");
        }

        //4 保存评论MongoDB
        ApComment apComment = new ApComment();
        apComment.setContent(content);
        apComment.setEntryId(dto.getArticleId());
        apComment.setType((short) 0);  // 文章
        apComment.setAuthorId(apUser.getId());
        apComment.setAuthorName(apUser.getName());
        apComment.setImage(apUser.getImage());
        apComment.setCreatedTime(new Date());  // 创建时间
        apComment.setUpdatedTime(new Date());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setFlag((short) 0);  // 普通评论
        mongoTemplate.save(apComment);

        //5 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}
